import type { NextConfig } from 'next';
import withPlugins from 'next-compose-plugins';
import withBundleAnalyzer from '@next/bundle-analyzer';

// 定义插件类型
type Plugin = [
  (config: NextConfig) => NextConfig,
  Record<string, any>?
];

// 插件配置
const plugins: Plugin[] = [
  [
    withBundleAnalyzer({
      enabled: process.env.ANALYZE === 'true',
    })
  ],
  // 示例：添加更多插件
  // [withPWA, {
  //   pwa: {
  //     dest: 'public',
  //     disable: process.env.NODE_ENV === 'development',
  //   }
  // }],
];

// Next.js 配置
const nextConfig: NextConfig = {
  reactStrictMode: true,
  poweredByHeader: false,
  compress: true,

  // 图片优化配置
  images: {
    domains: [],
    deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
    imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
  },

  // webpack 配置
  webpack: (config, { dev, isServer }) => {
    // 生产环境优化
    if (!dev && !isServer) {
      config.optimization.splitChunks = {
        chunks: 'all',
        minSize: 20000,
        maxSize: 244000,
        minChunks: 1,
        maxAsyncRequests: 30,
        maxInitialRequests: 30,
        cacheGroups: {
          defaultVendors: {
            test: /[\\/]node_modules[\\/]/,
            priority: -10,
            reuseExistingChunk: true,
          },
          default: {
            minChunks: 2,
            priority: -20,
            reuseExistingChunk: true,
          },
        },
      };
    }
    return config;
  },

  // 环境变量配置
  env: {
    NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000',
  },

  // 自定义构建指标
  onDemandEntries: {
    maxInactiveAge: 25 * 1000,
    pagesBufferLength: 2,
  },
};

// 导出配置
export default withPlugins(plugins, nextConfig);
